import err from './error.js'
import sys from './sys.js'
class ChineseNum {
	_lt10 = ['〇', '一', '二', '三', '四', '五', '六', '七', '八', '九', '十']
	constructor(day) {
		this.day = day
	}
	toString() {
		if (this.day <= 10) return this._lt10[this.day]
		if (this.day < 20) return this._lt10[10] + this._lt10[this.day % 10]
		if (this.day == 20) return '廿'
		if (this.day < 30) return '廿' + this._lt10[this.day % 10]
		if (this.day == 30) return '卅'
		return '卅' + this._lt10[this.day % 10]
	}
}
class ChinaRegion{
	constructor(province, city, district) {
		this.province = province
		this.city = city
		this.district = district
	}
	provinceShort(){
		if (this.province.endsWith('省')) return this.province.substr(0, this.province.length - 1);
		else if (this.province.endsWith('特别行政区')) return this.province.substr(0, this.province.length - 5);
		else if(this.province.endsWith('市')) return this.province.substr(0, this.province.length - 1)
		else {
			if (this.province.startsWith('新疆')) return '新疆';
			if (this.province.startsWith('西藏')) return '西藏';
			if (this.province.startsWith('宁夏')) return '宁夏';
			if (this.province.startsWith('广西')) return '广西';
			if (this.province.startsWith('内蒙古')) return '内蒙古';
			return this.province
		}
	}
	cityShort(){
		if(this.city.endsWith('市')) return this.city.substr(0, this.city.length - 1)
		else if (this.city == '市辖区') return ''
		return this.city
	}
	toString(){
		let province = this.provinceShort(), city = this.cityShort(), district = this.district
		if (this.province == '全部') return '中华人民共和国'
		if (this.city == '全部') city = ''
		if (this.district == '全部') district = ''
		if (this.district == this.city) district = ''
		if (this.province == this.city) city = ''
		return province + ' ' + city + ' ' + district;
	}
}

module.exports = {
	ChinaRegion: ChinaRegion,
	address2regionArr: function(address) {
		let p, c, d;
		if (address.indexOf('自治区')) p = address.substr(0, address.indexOf('自治区') + 3)
	},
	formatTimeMinute: function(d) {
		return d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate() + ' ' + d.getHours() + ':' + d.getMinutes()
	},
	chineseTime: function(d) {
		let yearStr = (d.getFullYear() + '').replace(/\d/g, c => new ChineseNum(parseInt(c)).toString())
		let monthStr = new ChineseNum(d.getMonth() + 1).toString()
		let dayStr = new ChineseNum(d.getDate()).toString();
		let dateStr = yearStr + '年' + monthStr + '月' + dayStr + '日'
		let hour = d.getHours()
		if (hour <= 3) return dateStr + '凌晨'
		if (3 < hour && hour < 11) return dateStr + '晨'
		if (11 <= hour && hour <= 14) return dateStr + '午'
		if (18 <= hour && hour <= 20) return dateStr + '晚'
		if (20 < hour) return dateStr + '夜'
		return dateStr
	},
	login: function() {
		return new Promise((resolve, reject) => {
			if (wx.getStorageSync('openid')) resolve(wx.getStorageSync('openid'))
			wx.login({
				success: function(res) {
					if (res.code) {
						wx.request({
							url: 'https://www.water-crystal.org/WechatApp/User/login',
							method: 'GET',
							data: {
								code: res.code
							},
							success: function(res) {
								wx.setStorageSync('openid', res.data.openid)
								resolve(res.data.openid)
							},
							fail: function(res) {
								reject(err.Login_SAE_Server_Failed(res))
							}
						});
					} else {
						reject(err.Login_Client_Failed(res))
					}
				},
				fail: function(res) {
					reject(err.Login_Client_Failed(res))
				}
			})
		})
	},
	genImgFromId: function(imgId) {
		const imgIdStr = '' + imgId
		const idStr = '0'.repeat(4 - imgIdStr.length) + imgIdStr
		return {
			id: imgId,
			path: `https://cdn.water-crystal.org/huazang/${idStr}.jpeg`
		}
	},

	freq: function(timeGap, fn) {
		let pre = Date.now()
		return function() {
			let t = Date.now() - pre;
			// console.log(t, timeGap)
			if (t >= timeGap) {
				let context = this;
				let args = arguments;
				fn.apply(context, args);
				pre = Date.now();
			}
		}
	},

	freqAsync: function(timeGap, asyncfn) {
		let pre = Date.now()
		return async function() {
			let t = Date.now() - pre;
			// console.log(t, timeGap)
			if (t >= timeGap) {
				let context = this;
				let args = arguments;
				await asyncfn.apply(context, args);
				pre = Date.now();
			}
		}
	},

	gps2distance: function(lon1, lat1, lon2, lat2) {
		function degree2radians(degree) {
			return degree * Math.PI / 180;
		}
		function haverSin(theta) {
			let v = Math.sin(theta / 2);
			return v * v;
		}
		const EARTH_RADIUS = 6371.0
		lat1 = degree2radians(lat1);
		lon1 = degree2radians(lon1);
		lat2 = degree2radians(lat2);
		lon2 = degree2radians(lon2);
		//差值
		let vLon = Math.abs(lon1 - lon2);
		let vLat = Math.abs(lat1 - lat2);
		//h is the great circle distance in radians, great circle就是一个球体上的切面，它的圆心即是球心的一个周长最大的圆。
		let h = haverSin(vLat) + Math.cos(lat1) * Math.cos(lat2) * haverSin(vLon);
		let distance = 2 * EARTH_RADIUS * Math.asin(Math.sqrt(h));
		return distance;
	}

}
